package com.taoyige.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.taoyige.AppConfig;
import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.bean.Address;
import com.taoyige.bean.AlipayResult;
import com.taoyige.bean.Order;
import com.taoyige.common.AlipaySignUtils;
import com.taoyige.common.UIHelper;
import com.taoyige.widget.LoadingDialog;

/**
 * 用户购买页面
 * @author zhuxun
 * @version 1.0
 * @date 2014-11-25 上午9:56:40
 */
public class BuyNowActivity extends BaseActivity {
	
	private AppContext appContext;
	
	private Handler handler;
	private Handler orderHandler;
	
	
	private LoadingDialog loading;
	private ImageButton returnBack;
	private ImageButton homePage;
	private TextView userHeadText;
	
	private RelativeLayout orderSubmitAddrRl;
	
	private TextView  order_main_order_user_name;
	private TextView order_main_order_user_location;
	private TextView order_main_order_buymoney_value;
	private TextView order_main_order_freight_value;
	private LinearLayout order_main_order_foot;
	private TextView order_main_order_foot_money;
	private TextView order_main_order_foot_save_money;
	private TextView order_main_order_paymoney;
	
	private Button orderMainSubmit;
	private LinearLayout order_submit_ll;
	private Address address;
	private Order order;
	private RelativeLayout buy_now_footer;
	private String userId="0";
	private int status;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_main);
		appContext=(AppContext) getApplication();
		userId=appContext.getLoginUid();
		this.initView();
		//initAddrData();
	}
	
	private void initView(){
		status = getIntent().getIntExtra("status", 0);
		returnBack=(ImageButton)findViewById(R.id.user_hear_return_back);
		homePage=(ImageButton)findViewById(R.id.user_hear_homePage);
		userHeadText=(TextView)findViewById(R.id.user_hear_text);
		userHeadText.setText("填写订单");
		if(status==1){
			returnBack.setOnClickListener(homeListener);
		}else{
//			returnBack.setOnClickListener(addressListener);
			returnBack.setOnClickListener(homeListener);
		}
		homePage.setOnClickListener(homeListener);
		
		
		orderSubmitAddrRl=(RelativeLayout)findViewById(R.id.order_submit_addr_rl);
		orderSubmitAddrRl.setOnClickListener(addressListener);
		orderMainSubmit=(Button) findViewById(R.id.order_main_submit);
		orderMainSubmit.setOnClickListener(submitListener);
		
		order_main_order_user_name=(TextView) findViewById(R.id.order_main_order_user_name);
		order_main_order_user_location=(TextView) findViewById(R.id.order_main_order_user_location);
		 order_main_order_buymoney_value=(TextView) findViewById(R.id.order_main_order_buymoney_value);
		order_main_order_freight_value=(TextView) findViewById(R.id.order_main_order_freight_value);
		order_main_order_foot_money=(TextView) findViewById(R.id.order_main_order_foot_money);
		order_main_order_foot_save_money=(TextView) findViewById(R.id.order_main_order_foot_all_money);
		order_main_order_paymoney=(TextView) findViewById(R.id.order_main_order_paymoney_value);
		
		order_main_order_foot=(LinearLayout) findViewById(R.id.order_main_order_foot);
		
		order_submit_ll=(LinearLayout) findViewById(R.id.order_submit_ll);
		buy_now_footer =(RelativeLayout)findViewById(R.id.buy_now_footer);
		
		if (!appContext.isNetworkConnected()){
			order_submit_ll.setVisibility(View.INVISIBLE);
			buy_now_footer.setVisibility(View.INVISIBLE);
			return;
		}
		
		order_submit_ll.setVisibility(View.INVISIBLE);
		order_main_order_foot.setVisibility(View.INVISIBLE);
		
		//init view
		
		order=(Order) getIntent().getSerializableExtra("order");
		address=(Address) getIntent().getSerializableExtra("address");
		
		if(appContext.isNetworkConnected()){
			order_submit_ll.setVisibility(View.VISIBLE);
			order_main_order_foot.setVisibility(View.VISIBLE);
		}
		
		if(!address.getId().equals("-1")){
			order_main_order_user_name.setText(address.getName()+"          "+address.getMobilephone());
			
			if(address.getCountyText()==null||address.getCountyText().equals("null")){
				order_main_order_user_location.setText(address.getProvinceText()+address.getCityText()+address.getDetails());
			}else{
				order_main_order_user_location.setText(address.getProvinceText()+address.getCityText()+address.getCountyText()+address.getDetails());
			}
			
			order.setUserID(userId);
			order.setProductID(Long.parseLong(order.getProduct().getId()));
			order.setAmount(order.getProduct().getPrice()+order.getProduct().getFreight());
			order.setTotalPrice(order.getProduct().getPrice());
			order.setOriPrice(order.getProduct().getOriPrice());
			order.setAddressInfo(address);
			orderMainSubmit.setTag(order);
			

		}else{
			initAddrData();
		}
			
		order_main_order_buymoney_value.setText(order.getProduct().getPrice()+"");
		order_main_order_freight_value.setText(order.getFreight()==null?"0":order.getFreight()+"");
		order_main_order_foot_money.setText(order.getTotalPrice()+"");
		order_main_order_paymoney.setText(order.getTotalPrice()+"");
		
		DecimalFormat df = new DecimalFormat("#.0");
		Double d=order.getProduct().getOriPrice()-order.getProduct().getPrice();
		order_main_order_foot_save_money.setText("为您节省:￥"+df.format(d));
		
	}
	

	private void initAddrData() {
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (loading != null)
					loading.dismiss();
				if (msg.what == 1 ) {
					if(msg.obj!=null){
						//如果有默认地址显示默认地址
						Address addr=(Address) msg.obj;
						
							order_main_order_user_name.setText(addr.getName()+"          "+addr.getMobilephone());
							
							if(addr.getCountyText()==null||addr.getCountyText().equals("null")){
								order_main_order_user_location.setText(addr.getProvinceText()+addr.getCityText()+addr.getDetails());
							}else{
								order_main_order_user_location.setText(addr.getProvinceText()+addr.getCityText()+addr.getCountyText()+addr.getDetails());
							}
							
							order.setUserID(userId);
							order.setProductID(Long.parseLong(order.getProduct().getId()));
							order.setAmount(order.getProduct().getPrice()+order.getProduct().getFreight());
							order.setTotalPrice(order.getProduct().getPrice());
							order.setOriPrice(order.getProduct().getOriPrice());
							order.setAddressInfo(addr);
							orderMainSubmit.setTag(order);
							
							order_submit_ll.setVisibility(View.VISIBLE);
							order_main_order_foot.setVisibility(View.VISIBLE);
					}else{
						((AppException) msg.obj).makeToast(BuyNowActivity.this);
					}
				} else{
					UIHelper.ToastMessage(BuyNowActivity.this, getString(R.string.app_run_code_error));
				}
				
			}
		};

		loading = new LoadingDialog(this);
		loading.show();
		
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					//Address  addr= appContext.getAddrDefault(appContext.getLoginUid());
					Address  addr= appContext.getAddrDefault(userId);
					msg.what = 1;
					msg.obj = addr;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	public View.OnClickListener submitListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			//TODO 保存订单和支付
			//先判断订单是否失效 
			Order order=(Order) v.getTag();
			if(order==null){
				UIHelper.ToastMessage(v.getContext(), R.string.msg_order_invalidate);
				return;
			}			
			orderAddAndPay(order);
		}
	};
	
	
	private void orderAddAndPay(final Order o) {
		orderHandler = new Handler() {
			public void handleMessage(Message msg) {
				if (loading != null)
					loading.dismiss();
				if (msg.what == 1 ) {
					if(msg.obj!=null){
						final Map<String, Object> map=(Map<String, Object>) msg.obj;
						
						AlipayResult resultObj = new AlipayResult((String) map.get("result"));
						String resultStatus = resultObj.getResultStatus();
						// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
						if (TextUtils.equals(resultStatus, "9000")) {
							//UIHelper.ToastMessage(BuyNowActivity.this, getString(R.string.pay_success));
							//更新订单
							//Order oo=appContext.orderPaid(orderId);
							new Thread() {
								public void run() {
									Message msg = new Message();
									try {
										String orderId=(String) map.get("orderId");
										Order oo=appContext.orderPaid(orderId);
										msg.what = 1;
										msg.obj = oo;
									} catch (AppException e) {
										e.printStackTrace();
										msg.what = -1;
										msg.obj = e;
									}
									//handler.sendMessage(msg);
								}
							}.start();
								finish();
							UIHelper.showUserCenter(BuyNowActivity.this,AppConfig.BADGE_ORDER_PAID);
						} else {
							// 判断resultStatus 为非“9000”则代表可能支付失败
							// “8000” 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
							if (TextUtils.equals(resultStatus, "8000")) {
								UIHelper.ToastMessage(BuyNowActivity.this, getString(R.string.pay_ing));
							} else if(TextUtils.equals(resultStatus, "6001")){
								UIHelper.ToastMessage(BuyNowActivity.this, getString(R.string.pay_cancel));
								UIHelper.showUserCenter(BuyNowActivity.this,AppConfig.BADGE_ORDER_NOPAID);
							}else{
								UIHelper.ToastMessage(BuyNowActivity.this, getString(R.string.pay_failed));
								UIHelper.showUserCenter(BuyNowActivity.this,AppConfig.BADGE_ORDER_NOPAID);
							}
							finish();
						}
						
					}else{
						((AppException) msg.obj).makeToast(BuyNowActivity.this);
					}
				}else if(msg.what==2&&msg.obj!=null){
					UIHelper.ToastMessage(BuyNowActivity.this,(String)msg.obj);
				} else{
					UIHelper.ToastMessage(BuyNowActivity.this, getString(R.string.app_run_code_error));
				}
				
			}
		};
		loading = new LoadingDialog(this);
		loading.show();
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Order o= appContext.orderAdd(order);
					
					if(o!=null&&o.getResult().getErrorCode()==200){
						order.setId(o.getId());
						String alipayOrderInfo=appContext.getAlipayOrderInfo(order);
						String sign = appContext.sign(alipayOrderInfo);
						
						try {
							sign = URLEncoder.encode(sign, "UTF-8");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
						final String payInfo = alipayOrderInfo + "&sign=\"" + sign + "\"&"+AlipaySignUtils.getSignType();
						
						// 构造PayTask 对象
						PayTask alipay = new PayTask(BuyNowActivity.this);
						// 调用支付接口
						String result = alipay.pay(payInfo);
						Map<String, Object> map=new HashMap<String, Object>();
						map.put("result", result);
						map.put("orderId", order.getId());
						msg.obj = map;
						msg.what = 1;
					}else if(o!=null&&o.getResult().getErrorCode()==500){
						String errorMsg = o.getResult().getErrorMessage();
						msg.obj = errorMsg;
						msg.what = 2;
					}else{
						msg.obj = null;
						msg.what = -1;
					}
					//msg.obj = o;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				orderHandler.sendMessage(msg);
			}
		}.start();
	}
	
	
	private View.OnClickListener addressListener = new View.OnClickListener(){
		@Override
		public void onClick(View v){
			Intent intent = new Intent(v.getContext(), AddressDetailActivity.class);
			intent.putExtra("order", order);
			intent.putExtra("status", 2);
			v.getContext().startActivity(intent);
			finish();
		}
	};
	
	private View.OnClickListener homeListener = new View.OnClickListener(){
		@Override
		public void onClick(View v){
			UIHelper.showHomePage(v.getContext());
			finish();
		}
	};
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = true;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(status==1){
				UIHelper.showHomePage(BuyNowActivity.this);
				finish();
			}else{
				UIHelper.showHomePage(BuyNowActivity.this);
//				Intent intent = new Intent(BuyNowActivity.this, AddressDetailActivity.class);
//				intent.putExtra("order", order);
//				intent.putExtra("status", 2);
//				BuyNowActivity.this.startActivity(intent);
				finish();
			}
		} 
		return flag;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
